<!-- three.js -->
<script src='vendor/three.js/build/three.js'></script> 
<script src='vendor/three.js/examples/js/libs/dat.gui.min.js'></script> 
<!-- js-aruco -->
<script src='../../../vendor/js-aruco/src/svd.js'></script> 
<script src='../../../vendor/js-aruco/src/posit1.js'></script> 
<script src='../../../vendor/js-aruco/src/cv.js'></script> 
<script src='../../../vendor/js-aruco/src/aruco.js'></script> 
<!-- threex-aruco -->
<script src='../threex-arucocontext.js'></script> 
<script src='../threex-arucodebug.js'></script>
<script src='../threex-arucodatgui.js'></script>

<div>
        <form>
                <label>clear canvas<input id='checkboxClearCanvas' name="imgsel" type="radio"></label>
                <br/>
                <label>draw video<input id='checkboxDrawVideo' name="imgsel" type="radio" checked="checked" ></label>
                <br/>
                <label>draw detector grey<input id='checkboxDetectorGrey' name="imgsel" type="radio"></label>
                <br/>
                <label>draw detector threshold<input id='checkboxDetectorThreshold' name="imgsel" type="radio"></label>
        </form>

        <label>draw marker corners<input id='checkboxMarkerCorners' type="checkbox" checked="checked" ></label>
        <br/>
        <label>draw marker ids<input id='checkboxMarkerId' type="checkbox" checked="checked" ></label>
        <br/>
        <label>draw contours contours<input id='checkboxContoursContours' type="checkbox"></label>
        <br/>
        <label>draw contours polys<input id='checkboxContoursPolys' type="checkbox"></label>
        <br/>
        <label>draw contours candiddates<input id='checkboxContoursCandidates' type="checkbox"></label>
</div>
<body style='background-color: darkgray;'>

        <div id='webGLContainer' style='display: inline;'></div>

        
        <script>
        var onRenderFcts = []   // init rendering loop

        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
        
        var videoElement = document.createElement('video')
        videoElement.autoplay = true
        

        //////////////////////////////////////////////////////////////////////////////
        //                Code Separator
        //////////////////////////////////////////////////////////////////////////////
        
        navigator.getUserMedia({video:true}, function (stream){
                        if (window.URL) {
                                videoElement.src = window.URL.createObjectURL(stream);
                        } else if (videoElement.mozSrcObject !== undefined) {
                                videoElement.mozSrcObject = stream;
                        } else {
                                videoElement.src = stream;
                        }
                },
                function(error){
                }
        );


        var arucoContext = new THREEx.ArucoContext({
                debug: true,
                canvasWidth: 640,
                canvasHeight: 480,
        })
        if( arucoContext.debug !== null ){
                document.body.appendChild(arucoContext.debug.canvasElement)
        }

	// here is how to setup a datGUI for fine tuning
	var datGUI	= new dat.GUI()
	THREEx.addArucoDatGui(arucoContext, datGUI)
                
        var markerSize = 1.0; //millimeters
        var arucoPosit = new POS.Posit(markerSize, arucoContext.canvas.width);
        
        var renderer = new THREE.WebGLRenderer();
        renderer.setClearColor(0xffffff, 1);
        renderer.setSize(arucoContext.canvas.width, arucoContext.canvas.height);
        document.getElementById('webGLContainer').appendChild(renderer.domElement);
        
        var sceneOrtho = new THREE.Scene();
        var cameraOrtho = new THREE.OrthographicCamera(-0.5, 0.5, 0.5, -0.5);
        sceneOrtho.add(cameraOrtho);
        
        var scenePersp = new THREE.Scene();
        var cameraPersp = new THREE.PerspectiveCamera(42, arucoContext.canvas.width / arucoContext.canvas.height, 0.01, 100);
        scenePersp.add(cameraPersp);


        onRenderFcts.push(function(){
                renderer.setSize(arucoContext.canvas.width, arucoContext.canvas.height);
                
		cameraPersp.aspect = renderer.domElement.width / renderer.domElement.height;
		cameraPersp.updateProjectionMatrix();		
        })
        
        //////////////////////////////////////////////////////////////////////////////
        //                Code Separator
        //////////////////////////////////////////////////////////////////////////////
        
        
        var videoTexture = new THREE.Texture(videoElement)
        videoTexture.minFilter = THREE.LinearFilter
        var geometry = new THREE.PlaneGeometry(1.0, 1.0)
        var material = new THREE.MeshBasicMaterial({
                map: videoTexture, 
                depthTest: false, 
                depthWrite: false
        })
        var videoMesh = new THREE.Mesh(geometry, material);
        videoMesh.position.z = -1;
        sceneOrtho.add(videoMesh);
        
        
        var geometry = new THREE.PlaneGeometry(1.0, 1.0, 10, 10)
        var material = new THREE.MeshBasicMaterial( {
                color: 'hotpink',
                wireframe: true
        } )
        var model = new THREE.Mesh(geometry, material);
        
        var arWorldRoot = new THREE.Group
        arWorldRoot.add(model)
        scenePersp.add(arWorldRoot);
        
        //////////////////////////////////////////////////////////////////////////////
        //                render loop
        //////////////////////////////////////////////////////////////////////////////
        var lastDetectionAt = null
        requestAnimationFrame(function onAnimationFrame(){
                
                // update videoMesh
                if( videoElement.videoWidth ){
                        videoMesh.material.map.needsUpdate = true;
                }
                
                var present = Date.now()/1000
                if( lastDetectionAt === null || present-lastDetectionAt >= 1/30){
                        lastDetectionAt = Date.now()/1000
                // if( videoElement.readyState >= videoElement.HAVE_CURRENT_DATA ){
                        
                        // detect markers in imageData
                        var detectedMarkers = arucoContext.detect(videoElement)
                        if( detectedMarkers.length > 0 ){
                                var detectedMarker = detectedMarkers[0]
                        
                                var markerSize = 1
                                arucoContext.updateObject3D(arWorldRoot, arucoPosit, markerSize, detectedMarker);
                                arWorldRoot.visible = true
                        }else{
                                arWorldRoot.visible = false
                        }  
                        
                        if( document.querySelector('#checkboxClearCanvas').checked )      arucoContext.debug.clear()
                        if( document.querySelector('#checkboxDrawVideo').checked )      arucoContext.debug.drawVideo(videoElement)
                        if( document.querySelector('#checkboxDetectorGrey').checked )      arucoContext.debug.drawDetectorGrey()
                        if( document.querySelector('#checkboxDetectorThreshold').checked )      arucoContext.debug.drawDetectorThreshold()
                        
                        if( document.querySelector('#checkboxMarkerCorners').checked )      arucoContext.debug.drawMarkerCorners(detectedMarkers)
                        if( document.querySelector('#checkboxMarkerId').checked )      arucoContext.debug.drawMarkerIDs(detectedMarkers)
                        if( document.querySelector('#checkboxContoursContours').checked )      arucoContext.debug.drawContoursContours()
                        if( document.querySelector('#checkboxContoursPolys').checked )      arucoContext.debug.drawContoursPolys()
                        if( document.querySelector('#checkboxContoursCandidates').checked )      arucoContext.debug.drawContoursCandidates()
                }
                
                // render scene
                renderer.autoClear = false;
                renderer.clear();
                renderer.render(sceneOrtho, cameraOrtho);
                renderer.render(scenePersp, cameraPersp);

                requestAnimationFrame(onAnimationFrame);
        });
        
        
	//////////////////////////////////////////////////////////////////////////////////
	//		render the whole thing on the page
	//////////////////////////////////////////////////////////////////////////////////

	// render the scene
	onRenderFcts.push(function(){
                renderer.autoClear = false;
                renderer.clear();
                renderer.render(sceneOrtho, cameraOrtho);
                renderer.render(scenePersp, cameraPersp);
	})

	// run the rendering loop
	var lastTimeMsec= null
	requestAnimationFrame(function animate(nowMsec){
		// keep looping
		requestAnimationFrame( animate );
		// measure time
		lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
		var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
		lastTimeMsec	= nowMsec
		// call each update function
		onRenderFcts.forEach(function(onRenderFct){
			onRenderFct(deltaMsec/1000, nowMsec/1000)
		})
	})        
        
</script>        


<style media="screen">
img {
        width: 196px;
        height: 196px;
        padding: 0em;
        margin: 0;
}
</style>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>

<div>
        <img src="images/1001.png"/>
        <!-- <img src="images/1002.png"/>
        <img src="images/1003.png"/>
        <img src="images/1004.png"/> -->
</div>        
</body>
